package com.bwie.service.impl;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bwie.utils.R;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.Type;
import com.bwie.mapper.TypeMapper;
import com.bwie.service.TypeService;
import org.springframework.web.multipart.MultipartFile;

@Service
public class TypeServiceImpl extends ServiceImpl<TypeMapper, Type> implements TypeService{

    @Autowired
    TypeMapper typeMapper;

    @Autowired
    FastFileStorageClient fileStorageClient;

    @Override
    public R getTypeTree() {
        List<Type> listAll = typeMapper.selectList(null);

        List<Tree<String>> treeList = TreeUtil.build(listAll, "0", (type, node) -> {
            node.setId(type.getTypeId().toString());
            node.setParentId(type.getTypePid().toString());
            node.setName(type.getTypeName());
            node.putExtra("typeStatus", type.getTypeStatus());
            node.putExtra("typeImage",type.getTypeImage());
            node.putExtra("typeTop",type.getTypeTop());
        });
        return R.ok().setData(treeList);
    }

    @Override
    public R addType(Type type) {
        QueryWrapper<Type> wrapper = new QueryWrapper<>();
        Type type1 = typeMapper.selectOne(wrapper.lambda().eq(Type::getTypeName, type.getTypeName()));
        if(type1!=null){
            return R.error().setMsg("名称已存在");
        }

        typeMapper.insert(type);
        return R.ok();
    }

    @Override
    public R uploadFileimages(MultipartFile file) {
        String extName = FileNameUtil.extName(file.getOriginalFilename());
        try {
            StorePath storePath = fileStorageClient.uploadFile(file.getInputStream(), file.getSize(),extName, null);
            String url="http://192.168.80.192:8888/"+storePath.getFullPath();
            return R.ok().setData(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.error().setMsg("上传失败");
    }

    @Override
    public R getSelectTypeList() {
        List<Type> listAll = typeMapper.selectList(null);

        List<Tree<String>> treeList = TreeUtil.build(listAll, "0", (type, node) -> {
            node.setId(type.getTypeId().toString());
            node.setParentId(type.getTypePid().toString());
            node.setName(type.getTypeName());
            node.putExtra("label", type.getTypeName());
            node.putExtra("value",type.getTypeId().toString());
        });
        return R.ok().setData(treeList);
    }
}
